package com.yj.agent.service;

import cn.com.yj.common.enums.Status;
import cn.com.yj.common.repository.BaseRepository;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yj.agent.bean.TAgentUserRateBean;
import com.yj.agent.bean.TAgentUserRechargeBean;
import com.yj.agent.bean.TOrgUserModel;
import com.yj.agent.bean.UserRateModel;
import com.yj.agent.mapper.AgentUserMapper;
import com.yj.agent.mapper.AgentUserRateMapper;
import com.yj.agent.mapper.AgentUserRechargeMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysnService {
    private final static Logger logger = LoggerFactory.getLogger(SysnService.class);
    @Autowired
    private AgentUserMapper agentUserMapper;
    @Autowired
    private AgentUserRechargeMapper agentUserRechargeMapper;
    @Autowired
    private AgentUserRateMapper agentUserRateMapper;


    public TOrgUserModel getUserInfo(String account) throws Exception {
        //创建一个httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder("http://47.96.31.84:84/WS/AgentInterface.ashx?action=getuserinfo");
        uriBuilder.addParameter("account", account);
        HttpGet get = new HttpGet(uriBuilder.build());
        //执行请求
        CloseableHttpResponse response = httpClient.execute(get);
        //取响应的结果
        int statusCode = response.getStatusLine().getStatusCode();
        logger.info(statusCode + "");
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        logger.info(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
        if (jsonArray == null || jsonArray.size() == 0) {
            return null;
        }
        TOrgUserModel userBean = new TOrgUserModel();
        userBean.setAccounts(jsonArray.getJSONObject(0).getString("UserID"));
        userBean.setUserID(jsonArray.getJSONObject(0).getString("UserID"));
        userBean.setRegisterDate(jsonArray.getJSONObject(0).getDate("RegisterDate"));
        userBean.setNickName(jsonArray.getJSONObject(0).getString("NickName"));
        //关闭httpclient
        response.close();
        httpClient.close();
        return userBean;
    }


//    @Scheduled(cron = "20 30 14 29 * ?")
//    public void scheduleRate() {
//        List<TAgentUserRechargeBean> list = agentUserRechargeMapper.queryBeans();
//        //插入充值记录后，开始计算分成金币给上级
//        //更新自己的贡献金币
//        List<TAgentUserRateBean> rateBeans = new ArrayList<>();
//        for (TAgentUserRechargeBean rechargeBean : list) {
//            UserRateModel userRateModel = agentUserMapper.getRate(rechargeBean.getGameId());
//            logger.info("userRateModel", userRateModel);
//            if (userRateModel == null || StringUtils.isBlank(userRateModel.getGameId2())) {
//                continue;
//            }
//            if (userRateModel.getProfitRate2() == null) {
//                logger.info("userRateModel:" + userRateModel.getGameId2() + "的 getProfitRate为空");
//                continue;
//            }
//            if (StringUtils.isBlank(userRateModel.getGameId1())) {
//                logger.info("userRateModel:只有一级", userRateModel);
//                //如果只有一级
//                long amount = rechargeBean.getAmount() * userRateModel.getProfitRate2().longValue() * 100;
//                //插入抽成明细表
//                TAgentUserRateBean rateBean = new TAgentUserRateBean();
//                rateBean.setGameId(rechargeBean.getGameId());
//                rateBean.setAgentGameId(userRateModel.getGameId2());
//                rateBean.setAmount(amount);
//                rateBean.setCreateTime(new Date());
//                rateBean.setStatus(Status.E.name());
//                rateBeans.add(rateBean);
//                logger.info("rateBean:只有一级", rateBean);
//                continue;
//            }
//            //如果有2级存在，则要更新一级和二级的抽成
//            if(userRateModel.getProfitRate1()==null||userRateModel.getSubProfitRate1()==null){
//                continue;
//            }
//            //二级收益
//            Float amount2 = rechargeBean.getAmount() * userRateModel.getSubProfitRate1() * 100;
//            //一级收益=一级总收益-二级收益
//            Float amount1 = rechargeBean.getAmount() * (userRateModel.getProfitRate1() - userRateModel.getSubProfitRate1()) * 100;
//            //插入抽成明细表
//            logger.info("userRateModel:有2级", userRateModel);
//            TAgentUserRateBean rateBean = new TAgentUserRateBean();
//            rateBean.setGameId(rechargeBean.getGameId());
//            rateBean.setAgentGameId(userRateModel.getGameId2());
//            rateBean.setAmount(amount2.longValue());
//            rateBean.setCreateTime(new Date());
//            rateBean.setStatus(Status.E.name());
//            logger.info("rateBean:二级", rateBean);
//            rateBeans.add(rateBean);
//            TAgentUserRateBean rateBean1 = new TAgentUserRateBean();
//            rateBean1.setGameId(rechargeBean.getGameId());
//            rateBean1.setAgentGameId(userRateModel.getGameId1());
//            rateBean1.setAmount(amount1.longValue());
//            rateBean1.setCreateTime(new Date());
//            rateBean1.setStatus(Status.E.name());
//            logger.info("rateBean:1级", rateBean);
//            rateBeans.add(rateBean1);
//        }
//        logger.info(rateBeans.toString());
//        if (!rateBeans.isEmpty()) {
//            Map rateMap = new HashMap();
//            rateMap.put("list", rateBeans);
//            agentUserRateMapper.insertList(rateMap);
//        }
//    }

    /**
     * 每天凌晨2点开始同步昨天已有玩家的充值数据
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void schedulePayInfo() {
        //获取当前系统时间，同步昨天一天的数据
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date now = calendar.getTime();
        logger.info("调度开始咯:" + new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = calendar.getTime();
        try {
            //对方接口的时间戳是10位，需要做下转换
            sysnUserPayInfo(String.format("%010d", yesterday.getTime() / 1000), String.format("%010d", now.getTime() / 1000));
            logger.info("调度结束咯:" + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sysnUserPayInfo(String startTime, String endTime) throws Exception {
        //创建一个httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder("http://47.96.31.84:84/WS/AgentInterface.ashx?action=getuserpayinfo");
        uriBuilder.addParameter("startTime", startTime);
        uriBuilder.addParameter("endTime", endTime);
        HttpGet get = new HttpGet(uriBuilder.build());
        //执行请求
        CloseableHttpResponse response = httpClient.execute(get);
        //取响应的结果
        int statusCode = response.getStatusLine().getStatusCode();
        logger.info(statusCode + "");
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        logger.info(result);
        //关闭httpclient
        response.close();
        httpClient.close();
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
        if (jsonArray == null || jsonArray.isEmpty()) {
            return;
        }
        List<TAgentUserRechargeBean> list = new ArrayList<>();
        for (Object obj : jsonArray) {
            JSONObject obj1 = (JSONObject) obj;
            TAgentUserRechargeBean bean = new TAgentUserRechargeBean();
            bean.setRecordId(obj1.getString("DetailID"));
            bean.setAmount(obj1.getLong("PayAmount"));
            bean.setRechargeTime(obj1.getDate("ApplyDate").getTime() + "");
            bean.setGameId(obj1.getString("userId"));
            bean.setStatus(Status.E.name());
            bean.setCreateTime(new Date());
            bean.setUpdateTime(new Date());
            list.add(bean);
        }
        Map map = new HashMap();
        map.put("list", list);
        logger.info(list.toString());
        agentUserRechargeMapper.insertList(map);
        //插入充值记录后，开始计算分成金币给上级
        //更新自己的贡献金币
        List<TAgentUserRateBean> rateBeans = new ArrayList<>();
        for (TAgentUserRechargeBean rechargeBean : list) {
            UserRateModel userRateModel = agentUserMapper.getRate(rechargeBean.getGameId());
            logger.info("userRateModel", userRateModel);
            if (userRateModel == null || StringUtils.isBlank(userRateModel.getGameId2())) {
                continue;
            }
            if (userRateModel.getProfitRate2() == null) {
                logger.info("userRateModel:" + userRateModel.getGameId2() + "的 getProfitRate为空");
                continue;
            }
            if (StringUtils.isBlank(userRateModel.getGameId1())) {
                logger.info("userRateModel:只有一级", userRateModel);
                //如果只有一级
                long amount = rechargeBean.getAmount() * userRateModel.getProfitRate2().longValue() * 100;
                //插入抽成明细表
                TAgentUserRateBean rateBean = new TAgentUserRateBean();
                rateBean.setGameId(rechargeBean.getGameId());
                rateBean.setAgentGameId(userRateModel.getGameId2());
                rateBean.setAmount(amount);
                rateBean.setCreateTime(new Date());
                rateBean.setStatus(Status.E.name());
                rateBeans.add(rateBean);
                logger.info("rateBean:只有一级", rateBean);
                continue;
            }
            //如果有2级存在，则要更新一级和二级的抽成
            if(userRateModel.getProfitRate1()==null||userRateModel.getSubProfitRate1()==null){
                continue;
            }
            //二级收益
            Float amount2 = rechargeBean.getAmount() * userRateModel.getSubProfitRate1() * 100;
            //一级收益=一级总收益-二级收益
            Float amount1 = rechargeBean.getAmount() * (userRateModel.getProfitRate1() - userRateModel.getSubProfitRate1()) * 100;
            //插入抽成明细表
            logger.info("userRateModel:有2级", userRateModel);
            TAgentUserRateBean rateBean = new TAgentUserRateBean();
            rateBean.setGameId(rechargeBean.getGameId());
            rateBean.setAgentGameId(userRateModel.getGameId2());
            rateBean.setAmount(amount2.longValue());
            rateBean.setCreateTime(new Date());
            rateBean.setStatus(Status.E.name());
            logger.info("rateBean:二级", rateBean);
            rateBeans.add(rateBean);
            TAgentUserRateBean rateBean1 = new TAgentUserRateBean();
            rateBean1.setGameId(rechargeBean.getGameId());
            rateBean1.setAgentGameId(userRateModel.getGameId1());
            rateBean1.setAmount(amount1.longValue());
            rateBean1.setCreateTime(new Date());
            rateBean1.setStatus(Status.E.name());
            logger.info("rateBean:1级", rateBean);
            rateBeans.add(rateBean1);
        }
        logger.info(rateBeans.toString());
        if (!rateBeans.isEmpty()) {
            Map rateMap = new HashMap();
            rateMap.put("list", rateBeans);
            agentUserRateMapper.insertList(rateMap);
        }
    }
}
